package com.xin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/*
* 给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出 和为目标值 target  的那 两个 整数，并返回它们的数组下标。

*你可以假设每种输入只会对应一个答案。但是，数组中同一个元素在答案里不能重复出现。

*你可以按任意顺序返回答案。
*
* */
public class TwoSum {
    public static void main(String[] args) {
        List result = twoSum(new int[]{1, 3, 8, 7, 5, 4, 4}, 8);
        List list = twoSum1(new int[]{1, 3, 8, 7, 5, 4, 4}, 8);
        list.stream().forEach(i -> System.out.println());
        twoSum11(new int[]{1, 3, 8, 7, 5, 4, 4}, 8);
        System.out.println(result);
    }

    private static List twoSum(int[] arr, int target){
        List<List<Integer>> resultTotal = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            for (int j = i+1; j < arr.length; j++) {
                List<Integer> result = new ArrayList<>();
                int sum = arr[i] + arr[j];
                if (target == sum) {
                    result.add(i);
                    result.add(j);
                    resultTotal.add(result);
                    continue;
                }
            }
        }

        return resultTotal;
    }
    private static List<int[]> twoSum1(int[] arr, int target){
        List<List<Integer>> resultTotal = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>(arr.length - 1);
        map.put(arr[0], 0);


        List<int[]> list = new ArrayList<>(arr.length - 1);
        for (int i = 1; i < arr.length; i++) {
            int other = target - arr[i];
            if (map.containsKey(other)) {
                list.add(new int[]{i, map.get(other)});
            }
            map.put(arr[i], i);
        }
        return list;
    }

    public static int[] twoSum11(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap(nums.length - 1);
        map.put(nums[1], 0);
        for (int i = 1; i < nums.length; i++) {
            int other = target - nums[i];
            if (map.containsKey(other)) {
                return new int[]{i, map.get(other)};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException();
    }
}




